﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VideoCache.Server.MVCWeb.Areas.Admin.Models;
using VideoCache.Server.BLL;
using System.Web.Security;

namespace VideoCache.Server.MVCWeb.Areas.Admin.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Admin/Login/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (UserBLL.ValidateUser(model.UserName, model.Password))
                    {
                        if (RoleBLL.IsUserInRole(model.UserName, "admin"))
                        {
                            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(model.UserName, true, 30);
                            string encryptTicket = FormsAuthentication.Encrypt(ticket);
                            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket);
                            authCookie.Path = "/Admin";
                            Response.Cookies.Add(authCookie);

                            return RedirectToAction("Index", "Home");
                        }
                    }

                    ModelState.AddModelError("Error", "账号或密码错误。");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("Error", ex.Message);
                }
            }

            return View(model);
        }
    }
}
